package com.isp.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    /**
     * token 过期时间
     */
    private static final int CALENDAR_FIELD = Calendar.MINUTE;
    private static final int CALENDAR_INTERVAL = 30;

    /**
     * 创建Build
     *
     * @param jwtKey           jwtKey，不传默认不加iss
     * @param calendarField    过期时间单位
     * @param calendarInterval 过期时间
     * @return Build
     */
    private static JWTCreator.Builder createTokenBuilder(String jwtKey, Integer calendarField, Integer calendarInterval) {
        // 加密方式
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        if (StringUtils.isNotBlank(jwtKey)) {
            map.put("iss", jwtKey);
        }
        // 签发时间
        Date iaDate = new Date();
        // 设置过期时间
        Calendar nowTime = Calendar.getInstance();
        //前者为时间单位，后者时间数量
        nowTime.add(calendarField == null ? CALENDAR_FIELD : calendarField
                , calendarInterval == null ? CALENDAR_INTERVAL : calendarInterval);
        Date expiresDate = nowTime.getTime();
        return JWT.create().withHeader(map)
                .withIssuedAt(iaDate)
                .withExpiresAt(expiresDate);
    }

    /**
     * 生成token
     *
     * @param payloadMap       payload信息
     * @param jwtKey           jwtKey，不传默认不加iss
     * @param jwtSecret        jwtSecret
     * @param calendarField    过期时间单位，不传默认分钟
     * @param calendarInterval 过期时间，不传默认30
     * @return token
     */
    public static String createToken(Map<String, String> payloadMap, String jwtKey, String jwtSecret, Integer calendarField, Integer calendarInterval) {
        JWTCreator.Builder builder = createTokenBuilder(jwtKey, calendarField, calendarInterval);
        return builder
                .withPayload(payloadMap)
                .sign(Algorithm.HMAC256(jwtSecret));
    }


    /**
     * 解析token
     *
     * @param token     token
     * @param jwtSecret jwtSecret
     * @return 解析的token信息
     */
    public static DecodedJWT verifyToken(String token, String jwtSecret) throws Exception {
        //解析方式和密钥
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build();
        DecodedJWT decodedJWT = JWT.decode(token);
        return verifier.verify(decodedJWT);
    }

    public static void main(String[] args) {
        Map<String, String> payloadMap = new HashMap<>();
        payloadMap.put("token", "BFAAB7AEC1FCC62CF12C018C7EB2B9391245C0B0DE61CC0F791908B4A1035974");
        payloadMap.put("id", "3");
        String token = createToken(payloadMap, "XWyuKfTnY6fnZKrBbkHrP2Xysc4dVqm6", "2qd3Mo6y3R6izA5CnJ5ZqE0kLr4AZNos", null, null);
        System.out.println(token);
        System.out.println("==============================");
        try {
            DecodedJWT jwt = verifyToken(token, "2qd3Mo6y3R6izA5CnJ5ZqE0kLr4AZNos");
            Map<String, Claim> jwtClaims = jwt.getClaims();
            String userId = jwtClaims.get("user_id").asString();
            System.out.println(userId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

